package net.hhk.twitter;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import net.hhk.connect.HTTPConnect;
import net.hhk.controller.SuggestAdapter;
import net.hhk.controller.SuggestManager;
import net.hhk.controller.TweetAdapter;
import net.hhk.controller.UserAdapter;
import net.hhk.controller.UserManager;
import net.hhk.controller.lazyload.ImageLoader;
import net.hhk.data.Base64;
import net.hhk.data.Constant;
import net.hhk.data.MySharePreferences;
import net.hhk.data.ThreadedRequest;
import net.hhk.data.Tweet;
import net.hhk.data.User;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Gallery;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class WriteTweetActivity extends Activity implements OnClickListener {
	private TextView character;
	private EditText text, text2;
	private TextWatcher textWatcher;
	private Button sendButton;
	static MySharePreferences sharePre;
	public String mention;
	public int isReply;
	public String previous_mention;
	private SuggestManager mgr;
	private SuggestAdapter mAdapter;
	private Boolean isSuggest = false;
	private String beforeSuggest;
	private String currentSuggestUser = "";
	private ListView list;
	private Boolean isSuggestAdded = false;
	private int currentPage = 1;
	private Boolean mLoading = false;
	private static final int MSG_APPEND_MORE_ITEMS = 0;
	private View mLoadMoreFooter;
	public LayoutInflater inflater;
	private Bitmap photoSdc = null;
	private Bitmap photoCapture = null;
	private ImageButton captureBtn, pictureBtn;
	private String ImageServerUrl = "";
	private static final int NUMBER_OF_ITEMS_REQUESTED = 6;
	private Context context = this;
	private ImageView upload, frame_picture_list, frame_picture;
	private String avatar;
	private String fullname;
	private ImageLoader imageLoader;
	private int tokenid = 0;
	private boolean isTweetAble = true;
	private long time;
	private String quote = "";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.write_tweet_layout);
		Bundle b = getIntent().getExtras();
		isReply = b.getInt("isReply");
		quote = b.getString("quote");
		if(quote ==null) quote = "";

		previous_mention = b.getString("mention");
		imageLoader = new ImageLoader(this);
		character = (TextView) findViewById(R.id.tweet_number_character);
		text = (EditText) findViewById(R.id.tweet_text);

		text.setInputType(text.getInputType()
				| EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS
				| EditorInfo.TYPE_TEXT_VARIATION_FILTER);
		text2 = (EditText) findViewById(R.id.edittext2);

		character.setText(Integer.toString(Constant.TWEET_LENGTH
				- text.getText().length()));
		sendButton = (Button) findViewById(R.id.tweet_doAction);
		sendButton.setOnClickListener(this);

		mgr = new SuggestManager(getApplicationContext());

		ImageButton mention_btn = (ImageButton) findViewById(R.id.write_tweet_mention);
		mention_btn.setOnClickListener(this);

		captureBtn = (ImageButton) findViewById(R.id.write_tweet_camera);
		captureBtn.setOnClickListener(this);

		pictureBtn = (ImageButton) findViewById(R.id.write_tweet_picture);
		pictureBtn.setOnClickListener(this);

		upload = (ImageView) findViewById(R.id.upload_picture);
		upload.setOnClickListener(this);

		frame_picture = (ImageView) findViewById(R.id.frame_picture_edittext);

		frame_picture_list = (ImageView) findViewById(R.id.frame_picture);

		Button cancel = (Button) findViewById(R.id.tweet_cancel);
		cancel.setOnClickListener(this);

		sharePre = (MySharePreferences) getApplicationContext();
		String VisitPerson = sharePre.getExitString("currentVisitUsername");
		String MyUsername = sharePre.getExitString("myUsername");
		if (quote.trim().length() > 0) {
			text.setText("\"" + quote + "\"");
		} else {
			if (!VisitPerson.equals(MyUsername))
				text.setText("@" + VisitPerson + " ");
		}

		showInfo();

		list = (ListView) findViewById(R.id.list);
		list.setOnScrollListener(mScrollListener);
		list.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {

				// selected item
				User user = (User) parent.getItemAtPosition(position);
				String product = user.getUsername();
				isSuggestAdded = true;
				String textAdd = product.substring(currentSuggestUser.length());
				addMention(textAdd + " ");
				isSuggest = false;

				list.setVisibility(View.GONE);
				tokenid = 0;

			}
		});

		inflater = LayoutInflater.from(this);
		mLoadMoreFooter = inflater.inflate(R.layout.profile, null);
		textWatcher = new TextWatcher() {
			public void afterTextChanged(Editable s) {
				setNumber();
			}

			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				time = System.currentTimeMillis();
				if (before > 0) {
					String suggestStr = getSuggestWhenDelete(s, start);
					if (suggestStr.length() > 0) {
						tokenid++;
						loadData(suggestStr, tokenid);
					} else {
						ListView list = (ListView) findViewById(R.id.list);
						list.setVisibility(View.GONE);
					}
				} else {
					if (!isSuggestAdded) {
						if (s.charAt(start) == ' ')
							list.setVisibility(View.GONE);
						else {
							String suggestStr = getSuggestWhenDelete(s,
									start + 1);
							if (suggestStr.length() > 0) {
								tokenid++;
								loadData(suggestStr, tokenid);
							}
						}
					} else {
						isSuggestAdded = false;
					}

				}
			}
		};
		text.addTextChangedListener(textWatcher);
		text.setSelection(text.getText().length());

		if (previous_mention != null)
			addMention(previous_mention);

	}

	private OnClickListener clickSearch = new OnClickListener() {

		public void onClick(View v) {
			// TODO Auto-generated method stub
			Intent i = new Intent(getApplicationContext(), SearchActivity.class);

			startActivity(i);

		}
	};

	public String getSuggestWhenDelete(CharSequence s, int pos) {
		String result = "";
		for (int i = pos - 1; i >= 0; i--) {
			char c = s.charAt(i);
			if (c == ' ') {
				return "";
			} else if (c == '@') {
				return result;
			}

			result = c + result;
		}
		return "";
	}

	public void setNumber() {
		int nrcharacter = Constant.TWEET_LENGTH - text.getText().length();
		// - ImageServerUrl.length();

		if (nrcharacter <= 0) {
			character.setTextColor(Color.RED);
		} else {
			character.setTextColor(Color.BLACK);
		}

		if (((nrcharacter == Constant.TWEET_LENGTH) && (ImageServerUrl.length() == 0))
				|| (nrcharacter < 0)) {
			sendButton.setEnabled(false);
			sendButton.setBackgroundResource(R.drawable.button_bg_default);
		} else {
			sendButton.setEnabled(true);
			sendButton.setBackgroundResource(R.drawable.btn_active_default);
		}
		if (nrcharacter < 0) {
			character.setText("-" + Integer.toString(-nrcharacter));
		} else
			character.setText(Integer.toString(nrcharacter));

		text2.setText(text.getText());
	}

	public void getSuggestName() {
		if (!isSuggest)
			return;
		String tweet_text = text.getText().toString();
		String suggest = "";
		if (beforeSuggest.length() > 0) {
			suggest = tweet_text.substring(beforeSuggest.length());
			tokenid++;
			loadData(suggest, tokenid);
		}
	}

	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.tweet_doAction:
			if (isReply > 0)
				reply();
			else
				tweet();
			// finish();
			break;
		case R.id.tweet_cancel:
			cancel();
			break;
		case R.id.write_tweet_mention:
			addMention(" @");
			isSuggest = true;
			beforeSuggest = text.getText().toString();
			break;
		case R.id.write_tweet_camera:
			if (photoSdc != null) {
				CharSequence text = "Can't capture more";
				int duration = Toast.LENGTH_SHORT;

				Toast toast = Toast.makeText(getApplicationContext(), text,
						duration);
				toast.show();
			} else {
				if (photoCapture != null) {
					AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
							context);

					alertDialogBuilder
							.setMessage(
									"Are you sure want to delete this picture?")
							.setCancelable(false)
							.setPositiveButton("Yes",
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog, int id) {
											captureBtn
													.setImageResource(R.drawable.ic_dialog_camera_default);
											deleteImageInServer(ImageServerUrl);
											upload.setVisibility(View.GONE);
											frame_picture
													.setVisibility(View.GONE);
											frame_picture_list
													.setVisibility(View.GONE);
											photoCapture = null;
											ImageServerUrl = "";
										}
									})
							.setNegativeButton("No",
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog, int id) {
											// if this button is clicked, just
											// close
											// the dialog box and do nothing
											dialog.cancel();
										}
									});

					// create alert dialog
					AlertDialog alertDialog = alertDialogBuilder.create();

					// show it
					alertDialog.show();

				} else {
					Intent cameraIntent = new Intent(
							android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
					startActivityForResult(cameraIntent,
							Constant.CAMERA_REQUEST);
				}
			}
			break;
		case R.id.write_tweet_picture:

			if (photoCapture != null) {
				CharSequence text = "Can't upload more";
				int duration = Toast.LENGTH_SHORT;

				Toast toast = Toast.makeText(getApplicationContext(), text,
						duration);
				toast.show();
			} else {
				if (photoSdc != null) {
					AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
							context);

					alertDialogBuilder
							.setMessage(
									"Are you sure want to delete this picture")
							.setCancelable(false)
							.setPositiveButton("Yes",
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog, int id) {
											pictureBtn
													.setImageResource(R.drawable.ic_dialog_photo_default);
											deleteImageInServer(ImageServerUrl);
											upload.setVisibility(View.GONE);
											frame_picture
													.setVisibility(View.GONE);
											frame_picture_list
													.setVisibility(View.GONE);
											ImageServerUrl = "";
											photoSdc = null;
										}
									})
							.setNegativeButton("No",
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog, int id) {
											// if this button is clicked, just
											// close
											// the dialog box and do nothing
											dialog.cancel();
										}
									});

					// create alert dialog
					AlertDialog alertDialog = alertDialogBuilder.create();

					// show it
					alertDialog.show();

				} else {
					Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
					intent.setType("image/*");
					intent.putExtra("return-data", true);
					startActivityForResult(intent, 1);
				}
			}

			break;
		case R.id.upload_picture:
			if ((photoSdc != null) || (photoCapture != null)) {
				AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
						context);

				alertDialogBuilder
						.setMessage("Are you sure want to delete this picture")
						.setCancelable(false)
						.setPositiveButton("Yes",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int id) {
										pictureBtn
												.setImageResource(R.drawable.ic_dialog_photo_default);
										deleteImageInServer(ImageServerUrl);
										upload.setVisibility(View.GONE);
										frame_picture.setVisibility(View.GONE);
										frame_picture_list
												.setVisibility(View.GONE);
										photoSdc = null;
										ImageServerUrl = "";
									}
								})
						.setNegativeButton("No",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int id) {
										// if this button is clicked, just
										// close
										// the dialog box and do nothing
										dialog.cancel();
									}
								});

				// create alert dialog
				AlertDialog alertDialog = alertDialogBuilder.create();

				// show it
				alertDialog.show();
			}
			break;

		default:
			break;
		}
	}

	public void tweet() {

		String tweet_text = text.getText().toString() + " " + ImageServerUrl;
		List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
		postParameters.add(new BasicNameValuePair("mention",
				getUserMention(tweet_text)));
		postParameters.add(new BasicNameValuePair("TweetText", tweet_text));
		postParameters
				.add(new BasicNameValuePair("url_images", ImageServerUrl));
		HTTPConnect http = HTTPConnect.getConnect();
		String result = http.doConnect(Constant.POST_TWEET, postParameters);
		sharePre.setExitInt("isNewTweet", 1);
		Intent i = new Intent(getApplicationContext(), MainActivity.class);
		i.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
		startActivity(i);
		finish();

	}

	public void reply() {

		String tweet_text = text.getText().toString();
		if (ImageServerUrl.length() > 0)
			tweet_text = tweet_text + " " + ImageServerUrl;
		List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
		postParameters.add(new BasicNameValuePair("TweetText", tweet_text));
		postParameters.add(new BasicNameValuePair("mention",
				getUserMention(tweet_text)));
		postParameters.add(new BasicNameValuePair("tweetid", Integer
				.toString(isReply)));
		postParameters
				.add(new BasicNameValuePair("url_images", ImageServerUrl));
		HTTPConnect http = HTTPConnect.getConnect();
		String result = http.doConnect(Constant.POST_REPLY, postParameters);
		sharePre.setExitInt("isNewTweet", 1);
		Intent i = new Intent(getApplicationContext(), MainActivity.class);
		i.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
		startActivity(i);
		finish();
	}

	public String getUserMention(String text) {
		String _mention = "";
		Pattern p = Pattern.compile("@(\\w|\\d|-|_){0,140}");

		Matcher result = p.matcher(text);
		while (result.find()) {
			String url = result.group(0);
			String username = url.substring(url.indexOf("@") + 1);
			_mention = _mention + username + ";";
		}

		return _mention;
	}

	public void addMention(String textToInsert) {
		// String text_temp = text.getText().toString();
		// text.setText(text_temp+ " @");

		int start = text.getSelectionStart();
		int end = text.getSelectionEnd();
		text.getText().replace(Math.min(start, end), Math.max(start, end),
				textToInsert, 0, textToInsert.length());

	}

	private void loadData(String suggestName, int _token) {
		final String suggest = suggestName;
		final int token = _token;
		if (!currentSuggestUser.equals(suggest)) {
			list.addFooterView(mLoadMoreFooter);
			currentSuggestUser = suggestName;
			currentPage = 1;
		}
		final long dtMili = System.currentTimeMillis();

		AsyncTask<String, Void, List<User>> asyncTask = new AsyncTask<String, Void, List<User>>() {

			/*
			 * (non-Javadoc)
			 * 
			 * @see android.os.AsyncTask#onPreExecute()
			 */
			@Override
			protected void onPreExecute() {
				super.onPreExecute();

			}

			@Override
			protected List<User> doInBackground(String... params) {
				// Following actions will be done in background
				List<User> result = mgr.getSocialFeed(Constant.GET_SUGGEST, 0,
						1, 6, suggest);
				if (token == tokenid)
					return result;
				else {
					result.clear();
					return result;
				}
			}

			/*
			 * (non-Javadoc)
			 * 
			 * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
			 */
			@Override
			protected void onPostExecute(List<User> result) {
				super.onPostExecute(result);

				if (token == tokenid) {
					mAdapter = new SuggestAdapter(WriteTweetActivity.this,
							result);
					mAdapter.notifyDataSetChanged();
					list.setAdapter(mAdapter);
					if (mAdapter.getCount() < NUMBER_OF_ITEMS_REQUESTED) {
						if (list.getFooterViewsCount() > 0)
							list.removeFooterView(mLoadMoreFooter);
						mLoading = false;
					}
					ListView list = (ListView) findViewById(R.id.list);

					if (result.size() > 0) {
						list.setVisibility(View.VISIBLE);

					} else {
						list.setVisibility(View.GONE);
					}
				}

			}
		};
		asyncTask.execute("Saurabh");
	}

	private void loadMoreItems() {
		mLoading = true;

		new Thread() {
			public void run() {
				try {
					// in this example, we just simply wait for 2 seconds
					Thread.sleep(2000);
					Message msg = mMainhandler.obtainMessage(
							MSG_APPEND_MORE_ITEMS, generateList());
					mMainhandler.sendMessage(msg);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			};
		}.start();
	}

	private Handler mMainhandler = new Handler() {
		public void handleMessage(Message msg) {

			switch (msg.what) {
			case MSG_APPEND_MORE_ITEMS:
				ArrayList newData = (ArrayList) msg.obj;
				if (mAdapter == null) {
					mAdapter = new SuggestAdapter(WriteTweetActivity.this,
							newData);
					list.setAdapter(mAdapter);
				} else {

					mAdapter.appendItems(newData);
				}

				if (newData.size() < NUMBER_OF_ITEMS_REQUESTED) {
					list.removeFooterView(mLoadMoreFooter);
				}
				mLoading = false;
				break;

			}

		}
	};

	private ArrayList generateList() {

		currentPage++;

		return (ArrayList<User>) mgr.getSocialFeed(Constant.GET_SUGGEST, 0,
				currentPage, NUMBER_OF_ITEMS_REQUESTED, currentSuggestUser);
	}

	private void checkLoadMore() {
		if (mLoading)
			return;

		/*
		 * if the loading footer is still there, then we will load more items
		 */
		if (list.getFooterViewsCount() != 0) {
			loadMoreItems();
		}
	}

	private OnScrollListener mScrollListener = new OnScrollListener() {

		public void onScrollStateChanged(AbsListView view, int scrollState) {
			// We have nothing to do with this right now
		}

		public void onScroll(AbsListView view, int firstVisibleItem,
				int visibleItemCount, int totalItemCount) {
			if (view.getLastVisiblePosition() >= 0) {
				if (view.getLastVisiblePosition() >= (totalItemCount - 1)) {

					checkLoadMore();
				}
			}
		}
	};

	protected void onActivityResult(int requestCode, int resultCode,
			android.content.Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		switch (requestCode) {
		case 1:
			if (requestCode == 1 && data != null && data.getData() != null) {
				Uri _uri = data.getData();

				if (_uri != null) {
					// User had pick an image.
					Cursor cursor = getContentResolver()
							.query(_uri,
									new String[] { android.provider.MediaStore.Images.ImageColumns.DATA },
									null, null, null);
					cursor.moveToFirst();

					// Link to the image
					final String imageFilePath = cursor.getString(0);

					File photos = new File(imageFilePath);
					photoSdc = decodeFile(photos);
					// b = Bitmap.createScaledBitmap(b, 150, 150, true);
					if (photoSdc != null) {
						pictureBtn
								.setImageResource(R.drawable.ic_dialog_photo_active_default);

					}

					upload.setVisibility(View.VISIBLE);
					upload.setImageBitmap(photoSdc);
					frame_picture.setVisibility(View.INVISIBLE);
					frame_picture_list.setVisibility(View.INVISIBLE);

					cursor.close();

				}
			}
			break;
		case Constant.CAMERA_REQUEST:
			photoCapture = (Bitmap) data.getExtras().get("data");
			if (photoCapture != null) {

				captureBtn
						.setImageResource(R.drawable.ic_dialog_camera_active_default);
			}
			ImageServerUrl = UploadBitmapToServer(photoCapture);
			ImageView upload = (ImageView) findViewById(R.id.upload_picture);

			upload.setVisibility(View.VISIBLE);
			upload.setImageBitmap(photoCapture);
			frame_picture.setVisibility(View.INVISIBLE);
			frame_picture_list.setVisibility(View.INVISIBLE);
			break;

		}

	};

	public String UploadBitmapToServer(Bitmap bm) {
		ByteArrayOutputStream stream = new ByteArrayOutputStream();
		bm.compress(Bitmap.CompressFormat.JPEG, 90, stream); // compress to
																// which
																// format you
																// want.
		byte[] byte_arr = stream.toByteArray();
		String image_str = Base64.encodeBytes(byte_arr);
		ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

		nameValuePairs.add(new BasicNameValuePair("imageBinary", image_str));
		HTTPConnect http = HTTPConnect.getConnect();
		String result = http.doConnect(Constant.POST_IMAGE, nameValuePairs);
		return result;
	}

	public void deleteImageInServer(String url) {
		ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

		nameValuePairs.add(new BasicNameValuePair("dir_file", url));
		HTTPConnect http = HTTPConnect.getConnect();
		String result = http.doConnect(Constant.DELETE_IMAGE, nameValuePairs);
	}

	private Bitmap decodeFile(File f) {
		try {
			// decode image size
			BitmapFactory.Options o = new BitmapFactory.Options();
			o.inJustDecodeBounds = true;
			BitmapFactory.decodeStream(new FileInputStream(f), null, o);

			// Find the correct scale value. It should be the power of 2.
			final int REQUIRED_SIZE = 70;
			int width_tmp = o.outWidth, height_tmp = o.outHeight;
			int scale = 1;
			while (true) {
				if (width_tmp / 2 < REQUIRED_SIZE
						|| height_tmp / 2 < REQUIRED_SIZE)
					break;
				width_tmp /= 2;
				height_tmp /= 2;
				scale++;
			}

			// decode with inSampleSize
			BitmapFactory.Options o2 = new BitmapFactory.Options();
			o2.inSampleSize = scale;
			return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
		} catch (FileNotFoundException e) {
		}
		return null;
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if (photoSdc != null) {
			final ThreadedRequest tReq = new ThreadedRequest();
			tReq.start(new Runnable() {
				public void run() {
					// This would stop whatever the other method
					// started
					// and let the user know
					ImageServerUrl = UploadBitmapToServer(photoSdc).trim();
					setNumber();

				}
			});
		}
	}

	public void showInfo() {

		final ImageView tweet_image = (ImageView) findViewById(R.id.tweet_image);
		TextView full_name = (TextView) findViewById(R.id.tweet_fullname);
		List<NameValuePair> postParameters = new ArrayList<NameValuePair>();

		HTTPConnect http = HTTPConnect.getConnect();
		String result = http.doConnect(Constant.USERINFO, postParameters);

		try {
			JSONObject obj = new JSONObject(result);
			fullname = obj.getString("screenName");
			avatar = obj.getString("avatar");
		} catch (Exception e) {
			e.printStackTrace();
		}
		full_name.setText(fullname);
		final ThreadedRequest tReq = new ThreadedRequest();
		tReq.start(new Runnable() {
			public void run() {
				imageLoader.DisplayImage(Constant.HOST + avatar, tweet_image);

			}
		});

	}

	public void cancel() {
		int nrcharacter = Constant.TWEET_LENGTH - text.getText().length()
				- ImageServerUrl.length();
		if (nrcharacter == Constant.TWEET_LENGTH) {
			finish();
		} else {
			AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
					context);

			alertDialogBuilder
					.setMessage("Are you sure want to cancel write tweet")
					.setCancelable(false)
					.setPositiveButton("Yes",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									pictureBtn
											.setImageResource(R.drawable.ic_dialog_photo_default);
									if (ImageServerUrl.length() > 0) {
										deleteImageInServer(ImageServerUrl);
										ImageServerUrl = "";
									}
									finish();
								}
							})
					.setNegativeButton("No",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									// if this button is clicked, just
									// close
									// the dialog box and do nothing
									dialog.cancel();
								}
							});

			// create alert dialog
			AlertDialog alertDialog = alertDialogBuilder.create();

			// show it
			alertDialog.show();
		}
	}

}